#include <stdio.h>
#include "Linux/Cursor.h"
#include "Linux/keyboard.h"
#include "Listeners.h"

#define ARTICLE 1
#define DICT 2
#define QUIT 0
#define PASS 3

static int nowstat = DICT;


void saveFile(void);
void saveDict(void);

void saveFile(void){
	ContentList* article = GET_CONTENT_ARTICLE();
	ContentList* filenames = GET_FILENAMES();
	int checkdNum = GET_CHECKED_DICT_NUM();
	struct String * filename = getContent(checkdNum, filenames);
	writeContent(article, filename -> str);
}

void saveDict(void){
	ContentList* filenames = GET_FILENAMES();
	struct String* tmp;
	int checkedNum = GET_CHECKED_DICT_NUM();
	int i;
	tmp = getContent(checkedNum, filenames);
	for(i = checkedNum; i > 0; i++){
		filenames -> strs[i - 1] = filenames -> strs[i];
	}
	filenames -> strs[0] = tmp;
	writeContent(filenames, CONF_FILE);
}

void initListener(void){
	wchar_t ws;
	int stat;

	clearScreen();
	consoleInit();
	drawScreen();
	initWriting();
	writeDicts();

	stat = getWchar(&ws);
	while(listenTo(stat, &ws) != QUIT){
		stat = getWchar(&ws);
	}

	saveFile();
	saveDict();
	clearScreen();
	consoleReset();
}

int listenTo(int stat, wchar_t* ws){
	if(nowstat == DICT){
		return dictListener(stat, ws);
	}else if(nowstat == ARTICLE){
		return articleListener(stat, ws);
	}
}

int dictListener(int stat, wchar_t* ws){
	switch(stat){
		case KEY_UP:
			dictScroll(-1);
			return PASS;
		case KEY_DOWN:
			dictScroll(1);
			return PASS;
		case KEY_LEFT:
			return QUIT;
			break;
		case KEY_RIGHT:
			nowstat = ARTICLE;
			initWriting();
			return PASS;
			break;
		case KEY_ESC:
			return QUIT;
			break;
		case KEY_BACK:
			dictBackSpace();
			return PASS;
			break;
		case KEY_NORMAL:
			break;
	}
	dictAppend(*ws);
}

int articleListener(int stat, wchar_t* ws){
	switch(stat){
		case KEY_UP:
			cursorUp();
			return PASS;
		case KEY_DOWN:
			cursorDown();
			return PASS;
		case KEY_LEFT:
			cursorLeft();
			return PASS;
		case KEY_RIGHT:
			cursorRight();
			return PASS;
		case KEY_ESC:
			saveFile();
			nowstat = DICT;
			return PASS;
		case KEY_BACK:
			cursorBack();
			return PASS;
		case KEY_NORMAL:
			break;
	}
	printSth(*ws);
}

